package cs342.uwosh.edu.QuizApp.database;

import java.io.*;
import java.nio.*;
import java.net.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class Encryption {
	URL url = null;
	HttpURLConnection connection = null;
	String password = "encryption";
	
	public void uploadScore(String targetURL, Integer value){
		try {
			url = new URL(targetURL);
			connection = (HttpURLConnection)url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type","application/octet-stream");
			connection.setRequestProperty("Content-Length", Long.toString(16));
			connection.setRequestProperty("Content-Language", "en-US");               
			connection.setUseCaches (false);
			connection.setDoInput(true);
			connection.setDoOutput(true);
			
			//call encrypt, send connection, score, password
            encrypt(connection, value, password);
		}
		catch (Exception e) {e.printStackTrace();} 
        finally {   
              if(connection != null) 
                connection.disconnect(); 
        }
	}//end of uploadScore
	
	
	public String downloadScore(String targetURL){
		String value = null;
		try{
			url = new URL(targetURL);
			value = decrypt(url, password);
		} catch(MalformedURLException e){System.out.println("URL incorrectly formed");}
		return value;
	}
	
	
	public String decrypt(URL url, String password){
//		String finalString = new String("");
		int value = 0;
		try {
			BufferedInputStream bis = new BufferedInputStream(url.openStream());
			// Create a key.
		    byte[] desKeyData = password.getBytes();
		    DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
		    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		    SecretKey desKey = keyFactory.generateSecret(desKeySpec);

		    // Use Data Encryption Standard cipher
		    Cipher des = Cipher.getInstance("des");
		    des.init(Cipher.DECRYPT_MODE, desKey);
		    
		    ByteArrayOutputStream baos = new ByteArrayOutputStream();
		    byte[] input = new byte[64];
			while (true) {
			   int bytesRead = bis.read(input);
			   System.out.println("bytesRead = " + bytesRead);
			   if (bytesRead == -1) break;
			   byte[] output = des.update(input, 0, bytesRead);
			   if (output != null) baos.write(output);
//			   finalString = finalString.concat(new String(output));
			
	        }
	        byte[] output = des.doFinal();
	        if (output != null) baos.write(output);
//	        finalString = finalString.concat(new String(output));
	        bis.close();
            
            ByteBuffer bb = ByteBuffer.wrap(output);
            value = bb.getInt();
        }
        catch (InvalidKeySpecException e) {System.err.println(e);}
        catch (InvalidKeyException e) {System.err.println(e);}
        catch (NoSuchAlgorithmException e) {
            System.err.println(e);
            e.printStackTrace();
        }
        catch (NoSuchPaddingException e) {System.err.println(e);}
        catch (BadPaddingException e) {System.err.println(e);}
        catch (IllegalBlockSizeException e) {System.err.println(e);}
        catch (IOException e) {System.err.println(e);}
		return Integer.toString(value);
	}//end of decrypt
	
	public void encrypt(HttpURLConnection connection, int score, String password){
		//convert score to a byte array
		ByteBuffer b = ByteBuffer.allocate(4);
		b.putInt(score);
		byte[] value = b.array();
		//String val = Integer.toString(score);
		
		try {
			InputStream in = new ByteArrayInputStream(value);
			
			// Create a key.
            byte[] desKeyData = password.getBytes();
            DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey desKey = keyFactory.generateSecret(desKeySpec);
			
			// Use Data Encryption Standard cipher
            Cipher des = Cipher.getInstance("des");
            des.init(Cipher.ENCRYPT_MODE, desKey);
            
            BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
            byte[] input = new byte[64];
            while (true) {
                int bytesRead = in.read(input);
					 System.out.println("bytesRead = " + bytesRead);
                if (bytesRead == -1) break;
                byte[] output = des.update(input, 0, bytesRead);
                if (output != null){
					 	bos.write(output);
						
					 }
            }
				byte[] output = des.doFinal();
            if (output != null) bos.write(output);
            in.close();
            bos.flush();
            bos.close();
			
/*			InputStream is = connection.getInputStream();
              BufferedReader rd = new BufferedReader(new InputStreamReader(is));
              String line;
              StringBuffer response = new StringBuffer(); 
              while((line = rd.readLine()) != null) {
                  response.append(line);
                  response.append("\n");
              }
              rd.close();
              System.out.println(response.toString());*/
		}
        catch (InvalidKeySpecException e) {System.err.println(e);}
        catch (InvalidKeyException e) {System.err.println(e);}
        catch (NoSuchAlgorithmException e) {
            System.err.println(e);
            e.printStackTrace();
        }
        catch (NoSuchPaddingException e) {System.err.println(e);} 
        catch (BadPaddingException e) {System.err.println(e);}
        catch (IllegalBlockSizeException e) {System.err.println(e);}
        catch (IOException e) {System.err.println(e);}
	}
}
